<template>
  <div id="cesium-container">

    <div v-if="data.length" class="flowinfo" :style="{left:position.x+10+'px',top:position.y-15+'px'}">
      <div class="arrows"></div>
      <div class="right">
        <div class="content">
          <div v-for="(item,index) in data" :key="index" class="item"
               :style="{backgroundColor:index%2==0?'rgb(242, 242, 242)':'rgb(250, 250, 250)'}">
            <div class="lf">
              <span :title="item.key">{{item.key}}:</span>
            </div>
            <div class="rg">
              <span :title="item.val"> {{item.value}}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
  import Earth from '@/js/earth/earth'
  import {BaseLayerType, LayerCatetory, LayerType} from '@/js/earth/EarthConstant'

  import {get, post} from '@/api/index'
  // import 'cesium-tdt'

  export default {
    name: "Earth",
    components: {},
    props: [],
    computed: {},
    data() {
      return {
        moveHandler: null,
        position: {},
        data: []
      }
    },
    created() {

    },
    mounted() {
      window.viewer = Earth.init('cesium-container');
      Earth.addBaseLayers(viewer);

      this.testClip();
      // this.test(); //宁夏地类图斑地图
      // this.test2(); //白膜
      // this.test4(); //矢量注记
      // this.test3();
      // this.test00();

      this.earthEvent();
    },
    methods: {
      earthEvent() {
        let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        handler.setInputAction((e) => {
          this.pickEntity(e.position);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      },


      testClip(){

        // let provider = new Cesium.UrlTemplateImageryProvider({
        //   url: 'http://10.240.142.1:8091/mapserver/vmap/LYHX_QG/getMAP?tilesize=512&styleId=10&x={x}&y={y}&l={l}',
        //   tilingScheme: new Cesium.GeographicTilingScheme(),
        //   tileWidth: 512,
        //   tileHeight: 512,
        //   customTags: {
        //     l: function(imageryProvider, x, y, level) {
        //       return level + 2;
        //     }
        //   }
        // });


        let provider = new Cesium.VTileImageryProvider({
          url: 'http://10.240.142.1:8091/mapserver/vmap/LYHX_QG/getMAP',
          styleId: '10',
          // control: control,
          enableRequestLabel:false,
        });


        let west = 90, south = 30, east = 110, north = 40;
        let layer = new Cesium.ImageryLayer(provider, {
          // rectangle: Cesium.Rectangle.fromDegrees(west, south, east, north)
        });
        viewer.imageryLayers.add(layer);
      },

      /**
       * 矢量瓦片后端瓦片加载
       */
      test() {
        let param = {
          id: 'v1',
          name: '区划边界',
          type: LayerType.VTILE,
          params: {
            url: 'http://192.98.8.88:8094/mapserver/vmap/DLTBPT20161205/getMAP?tilesize=512&styleId=DLTB&x={x}&y={y}&l={l}',
          }
        }
        Earth.addLayer(param.params, param, viewer);
      },


      /**
       * 白膜加载
       */
      test2() {
        let model_datasource = new Cesium.CustomDataSource('zhejiang_model_data');
        viewer.dataSources.add(model_datasource);

        let provider = new Cesium.EntityTileServiceProvider({
          url: 'http://ditu.zjzwfw.gov.cn/mapserver/data/zjvmap201904_fangwu/getData?styleId=tdt_biaozhunyangshi_2017&tilesize=256&x={TileCol}&y={TileRow}&l={TileMatrix}',
          layer: 'zhejiang_model_data',
          rectangle: new Cesium.Rectangle.fromDegrees(118, 27, 123, 31.5),
          minimumLevel: 17,
          maximumLevel: 17,
          tileWidth: 256,
          tileHeight: 256,
          tileMatrixLabels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
          // subdomains:['ditu0','ditu1','ditu2','ditu3','ditu4','ditu5','ditu6'],
          entities: model_datasource.entities,
          modelLayers: ['面状居民地']
        })
        viewer.tileServiceLayers.addTileServiceProvider(provider);
      },

      /**
       * 属性拾取
       * @param x
       * @param y
       * @param z
       */
      pickServer(x, y, z) {
        this.data = [];
        let styleId = "tdt_biaozhunyangshi_2017";
        let url = 'http://ditu.zjzwfw.gov.cn/mapserver/data/zjvmap201904_fangwu/getData'
        let pickUrl = url.replace(/data\//, '').replace(/getData/, 'tdt_biaozhunyangshi_2017') + `/pickup?level=${z}&lon=${x}&lat=${y}&styleId=${styleId}`; //属性拾取地址
        get(pickUrl).then(re => {
          let arr = [];
          for (let key in re) {
            let obj = re[key];
            for (let k in obj) {
              let o = obj[k];
              for (let kk in o) {
                arr.push({
                  key: kk,
                  value: o[kk]
                })
              }
            }
          }
          this.data = arr;
        });
      },

      /**
       * 实体拾取
       * @param position
       */
      pickEntity(position) {
        this.data = [];
        this.updatePosition(position)
        let obj = viewer.scene.pick(position);
        if (obj) {
          let entity = obj.id;
          if (entity && entity.polygon && entity.polygon.hierarchy) {
            let positions = entity.polygon.hierarchy.getValue().positions;
            let rect = Cesium.Rectangle.fromCartesianArray(positions);
            let centerCartographic = Cesium.Rectangle.center(rect);
            let x = Cesium.Math.toDegrees(centerCartographic.longitude)
            let y = Cesium.Math.toDegrees(centerCartographic.latitude)
            let z = Earth.getStatusParam(viewer).mapLevel;
            if (z > 19) z = 19;
            this.pickServer(x, y, z)
          }
        }
      },

      /**
       * 实时修改弹框位置
       * @param position
       */
      updatePosition(position) {
        let that = this;
        let cartesian2 = new Cesium.Cartesian2(position.x, position.y);
        let cartesian3 = viewer.scene.globe.pick(viewer.camera.getPickRay(cartesian2), viewer.scene);
        let scene = viewer.scene;
        let picked = scene.pick(cartesian2);
        if (Cesium.defined(picked)) {
          let entity = Cesium.defaultValue(picked.id, picked.primitive.id);
          if (entity instanceof Cesium.Entity) {
            this.position = cartesian2;
            this.moveHandler = viewer.scene.postRender.addEventListener(function () {
              let uppos = Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene, cartesian3);
              if (that.position.x !== uppos.x || that.position.y !== uppos.y) {
                that.position = uppos;
              }
            });
          }
        }
      },

      /**
       * 注记测试
       */
      test3() {
        let zhejiang_vectortile_poi_annotation_datasource = new Cesium.CustomDataSource('zhejiang_vectortile_poi_annotation');
        viewer.dataSources.add(zhejiang_vectortile_poi_annotation_datasource);
        let zhejiangLabelStyleInfo = new Cesium.AssociativeArray();
        zhejiangLabelStyleInfo.set('POI', {idIndex: 0, textIndex: 2, styleName: 'POI'});
        zhejiangLabelStyleInfo.set('行政区划点', {idIndex: 0, textIndex: 1, styleName: '居民点'});
        viewer.tileServiceLayers.addTileServiceProvider(new Cesium.EntityTileServiceProvider({
          url: 'http://ditu.zjzwfw.gov.cn/mapserver/label/zjvmap/getDatas/?styleId=tdt_biaozhunyangshi_2017&tilesize=256&x={TileCol}&y={TileRow}&l={TileMatrix}',
          layer: 'zhejiang_vectortile_poi',
          texureUrl: 'http://ditu.zjzwfw.gov.cn/mapserver/styleinfo/zjvmap/tdt_biaozhunyangshi_2017/label/texture.js',
          layerDescriptionFile: '../../zjvmap-test.json',
          rectangle: new Cesium.Rectangle.fromDegrees(118, 27, 123, 31.5),
          minimumLevel: 6,
          maximumLevel: 16,
          clamped2TerrainLevel: 10,
          tileWidth: 256,
          tileHeight: 256,
          tileMatrixLabels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
          // subdomains:['ditu0','ditu1','ditu2','ditu3','ditu4','ditu5','ditu6'],
          entities: zhejiang_vectortile_poi_annotation_datasource.entities,
          labelLayers: ['POI', '行政区划点'],//,'水系点'
          labelStyleInfo: zhejiangLabelStyleInfo
        }));
      },

      /**
       * 注记测试
       */
      test4() {
        let dltb_datasource = new Cesium.CustomDataSource('dltb_datasource');
        viewer.dataSources.add(dltb_datasource);
        let zhejiangLabelStyleInfo = new Cesium.AssociativeArray();
        // zhejiangLabelStyleInfo.set('POI', { idIndex: 0, textIndex: 2, styleName: 'POI' });
        // zhejiangLabelStyleInfo.set('行政区划点', { idIndex: 0, textIndex: 1, styleName: '居民点' });
        viewer.tileServiceLayers.addTileServiceProvider(new Cesium.EntityTileServiceProvider({
          url: 'http://192.98.8.88:8094/mapserver/label/DLTBPT20161205/getData/?styleId=DLTB&tilesize=256&x={TileCol}&y={TileRow}&l={TileMatrix}',
          layer: 'DLTBPT20161205_注记',
          texureUrl: '',
          layerDescriptionFile: '/ime-cloud/style/base/system/getStyle.do?belongService=DLTBPT20161205&styleId=DLTB', // /ime-cloud/style/base/system/getStyle.do?belongService=DLTBPT20161205&styleId=DLTB   // './data/DLTB.json'
          rectangle: new Cesium.Rectangle.fromDegrees(105, 35, 107, 41),
          minimumLevel: 6,
          maximumLevel: 16,
          clamped2TerrainLevel: 10,
          tileWidth: 256,
          tileHeight: 256,
          tileMatrixLabels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
          entities: dltb_datasource.entities,
          labelLayers: ['DLTBPT20161205'],
          labelStyleInfo: zhejiangLabelStyleInfo
        }));
      },


      /**
       * 创建cesium 白模图层
       * @param {*} url
       * @param {*} layerMeta
       */
      test00() {
        const houseLayer = new Cesium.ImageryLayer(new Custom.HouseTileServiceImageryProvider(viewer, {
          url: "http://172.16.66.36:8091/mapserver/data/JinanFW/getData?x={x}&y={y}&l={z}&styleId=JinanFW&tilesize=512",
          tilingScheme: new Cesium.GeographicTilingScheme({
            numberOfLevelZeroTilesX: 2,
            numberOfLevelZeroTilesY: 1
          }),
          tileMatrixLabels: ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21'],
          maximumLevel: 19,
          tileWidth: 512,
          tileHeight: 512,
          // 是否需要数据解码
          needDecode: false,
          // 房屋颜色
          fillColor: "#FFFFFF",
          // 房屋透明度
          alpha: 0.6,
          // 房屋图层
          filterLayerId: "jinanfw", // '面状居民地',
          // 房屋高度字段
          heightProperty: "floor", // 'floor',
          // 高度缩放比例,即每层高3.2米
          heightScale: "3"
        }))

        viewer.imageryLayers.add(houseLayer);

      }

    },
    beforeDestroy() {
      if (this.moveHandler) {
        this.moveHandler.call();
      }
    }
  }
</script>

<style scoped lang="less">
  #cesium-container {
    height: 100%;
  }

  .flowinfo {
    z-index: 995;
    position: absolute;
    color: black;
    overflow-y: auto;
    display: flex;

    .arrows {
      background: transparent;
      width: 0;
      height: 0;
      margin-top: 5px;
      border-top: 13px solid transparent;
      border-right: 26px solid rgb(210, 210, 210);
      border-bottom: 13px solid transparent;
      display: inline-block;
      vertical-align: top;
    }

    .right {
      display: flex;
      flex-direction: column;
      background: rgb(210, 210, 210);
      -webkit-box-shadow: #999 0 0 8px;
      -moz-box-shadow: #999 0 0 8px;
      box-shadow: #999 0 0 8px;
      padding: 8px;

      .content {
        display: flex;
        flex-direction: column;
        max-height: 300px;
        width: 300px;
        overflow-y: auto;

        .item {
          display: flex;
          height: 30px;
          background: #ffffff;
          cursor: pointer;

          .lf {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            flex: 1;
            height: 100%;
            padding-left: 10px;
            color: rgb(57, 128, 195);

            > span {
              text-overflow: ellipsis;
              white-space: nowrap;
              overflow: hidden;
            }
          }

          .rg {
            display: flex;
            align-items: center;
            flex: 1;
            height: 100%;
            padding-left: 10px;
            padding-right: 4px;

            > span {
              text-overflow: ellipsis;
              white-space: nowrap;
              overflow: hidden;
            }
          }
        }
      }
    }
  }
</style>
<style>
  .cesium-credit-logoContainer {
    display: none !important;
  }

  .cesium-credit-expand-link {
    display: none !important;
  }
</style>
